package wikibooks;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 *
 * @author Derbeth
 */
public class CacheProviderImpl implements CacheProvider {

    private String toSafeFilename(String name) {
        StringBuilder sb = new StringBuilder(name.length());
        for (int i = 0; i < name.length(); ++i) {
            char c = name.charAt(i);
            String letter = name.substring(i, i+1);
            if (letter.matches("[a-zA-Z_ 0-1.]")) {
                sb.append(letter);
            } else {
                sb.append(letter.hashCode() % 100);
            }
        }
        return sb.toString();
    }

    private String keyToFilename(String key) {
        String directory = System.getProperty("java.io.tmpdir") + File.separator;
        return directory + toSafeFilename(key);
    }

    public boolean hasInCache(String key) {
        return new File(keyToFilename(key)).exists();
    }

    public void put(String key, String value) {
        File file = new File(keyToFilename(key));
        file.deleteOnExit();
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(file));
            writer.append(value);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String get(String key) {
        File file = new File(keyToFilename(key));
        if (!file.exists()) {
            return null;
        }
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            StringBuilder sb = new StringBuilder();
            String line;
            int aChar;
            while ((aChar = reader.read()) != -1) {
                sb.append((char)aChar);
            }
            /*while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }*/
            return sb.length() > 0 ? sb.toString() : null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
